<?php
namespace Components\Account\User;

class Validation extends \Phalcon\Validation {
	public function execute($data) {
		$result = [];
		$validationMessages = $this -> validate($data);
		if($validationMessages -> valid()) {
			return ['code'=>-1,'message'=>$validationMessages[0]->getMessage()];
		} else {
			return ['code'=>0,'data'=>$data];
		}
	}

	public function addCaptcha($parameter = []) {
		return $this -> rules('captcha',[
			new \Phalcon\Validation\Validator\PresenceOf()
		]);
		return $this;
	}

	public function addPAccount() {
		return $this -> rules('p_account',[
			new \Phalcon\Validation\Validator\Callback([
				'message' => '推荐人不存在',
				'callback' => function($data) {
					if(!isset($data['p_account']) || empty($data['p_account'])) {
						return true;
					}

					if(Model::findFirst(['account = "' . $data['p_account'] . '"'])) {
						return true;
					}
					return false;
				}
			])
		]);
	}

	public function addCellphone() {
		return $this -> rules('cellphone',[
			new \Phalcon\Validation\Validator\PresenceOf(),
			new \Phalcon\Validation\Validator\StringLength([
				'min' => 11
			])
		]);
	}

	public function addCellphoneUniqueness() {
		return $this -> rules('cellphone',[
			new \Phalcon\Validation\Validator\PresenceOf(),
			new \Phalcon\Validation\Validator\StringLength([
				'min' => 11
			]),
			new \Phalcon\Validation\Validator\Uniqueness([
				'model' => new Model(),
				'message' => '手机号已存在'
			])
		]);
	}

	public function addAccount() {
		return $this -> rules('account',[
			new \Phalcon\Validation\Validator\PresenceOf(),
			new \Phalcon\Validation\Validator\StringLength([
				'min' => 6
			])
		]);
	}

	public function addAccountUniqueness() {
		return $this -> rules('account',[
			new \Phalcon\Validation\Validator\PresenceOf(),
			new \Phalcon\Validation\Validator\StringLength([
				'min' => 6
			]),
			new \Phalcon\Validation\Validator\Uniqueness([
				'model' => new Model(),
				'message' => '账号已存在'
			])
		]);
	}

	public function addPassword() {
		return $this -> rules('password',[
			new \Phalcon\Validation\Validator\PresenceOf(),
			new \Phalcon\Validation\Validator\StringLength([
				'min' => 6
			])
		]);
	}

	public function addSafePassword() {
		return $this -> rules('safe_password',[
			new \Phalcon\Validation\Validator\PresenceOf(),
			new \Phalcon\Validation\Validator\StringLength([
				'min' => 6
			])
		]);
	}

	public function addLevel() {
		return $this -> rules('level',[
			new \Phalcon\Validation\Validator\InclusionIn([
				'domain' => [1, 2, 3, 4]
			])
		]);
	}

	public function addStatus() {
		return $this -> rules('status',[
			new \Phalcon\Validation\Validator\InclusionIn([
				'domain' => [0, 1, 2]
			])
		]);
	}
}
